package com.protocol;

import android.util.Log;

import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import cz.msebera.android.httpclient.HttpResponse;
import cz.msebera.android.httpclient.NameValuePair;
import cz.msebera.android.httpclient.client.ClientProtocolException;
import cz.msebera.android.httpclient.client.HttpClient;
import cz.msebera.android.httpclient.client.entity.UrlEncodedFormEntity;
import cz.msebera.android.httpclient.client.methods.HttpPost;
import cz.msebera.android.httpclient.impl.client.DefaultHttpClient;
import cz.msebera.android.httpclient.message.BasicNameValuePair;
import cz.msebera.android.httpclient.util.EntityUtils;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static android.content.ContentValues.TAG;

public class HttpAsync {

    public final static OkHttpClient mOkHttpClient = new OkHttpClient();

    public static Call gethttp(String path) {
        Request request = new Request.Builder()
                .url(path)
                .build();
        //new call
        Call call = mOkHttpClient.newCall(request);
        return call;
    }

    public static Call posthttp(String jsonString, String path) {
        Request request = new Request.Builder()
                .url(path)
                .post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonString.toString()))
                .build();
        //new call
        Call call = mOkHttpClient.newCall(request);
        return call;
    }

    public static String getCookie(String url) {
        HttpURLConnection.setFollowRedirects(true);
        HttpURLConnection conn = null;
        try {
            conn = (HttpURLConnection) new URL(url).openConnection();
//            conn.setRequestProperty("Cookie", "PHPSESSID=str_from_server");
            conn.setRequestMethod("GET");
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36");
//            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Content-Language", "zh-cn");
            conn.setRequestProperty("Connection", "keep-alive");
            conn.setRequestProperty("Cache-Control", "no-cache");
            conn.setConnectTimeout(5000);
            conn.connect();
            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                String cookieskey = "Set-Cookie";
                Map<String, List<String>> maps = conn.getHeaderFields();
                List<String> coolist = maps.get(cookieskey);
                Iterator<String> it = coolist.iterator();
                StringBuffer sbu = new StringBuffer();
                sbu.append("eos_style_cookie=default; ");
                while (it.hasNext()) {
                    sbu.append(it.next());
                }
                System.out.println(sbu.toString());
                return sbu.toString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String getCookie(String username, String password, String loginAction) throws Exception {
        //登录
        URL url = new URL(loginAction);
//        String param = "username="+username+"&password="+password;
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true);
//        conn.setUseCaches(false);
        conn.setRequestMethod("GET");
//        OutputStream out = conn.getOutputStream();
//        out.write(param.getBytes());
//        out.flush();
//        out.close();
        String sessionId = "";
        String cookieVal = "";
        String key = null;
        //取cookie
        for (int i = 1; (key = conn.getHeaderFieldKey(i)) != null; i++) {
            if (key.equalsIgnoreCase("set-cookie")) {
                cookieVal = conn.getHeaderField(i);
                cookieVal = cookieVal.substring(0, cookieVal.indexOf(";"));
                sessionId = sessionId + cookieVal + ";";
            }
        }
        return sessionId;
    }

    public static String postData() {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("https://example.com/login.aspx");

        try {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("txtUsername", "user"));
            nameValuePairs.add(new BasicNameValuePair("txtPassword", "123"));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            HttpResponse response = httpclient.execute(httppost);
            String responseAsText = EntityUtils.toString(response.getEntity());
            Log.v(TAG, "Response from req: " + responseAsText);
            return responseAsText;

        } catch (ClientProtocolException e) {

        } catch (IOException e) {

        }
        return null;
    }
}
